<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>复选框的全选和取消全选</title>
</head>
<body>
<script type="text/javascript">
    window.onload=function (){
        var firstChk=document.getElementById("firstChk");
        var aihaos=document.getElementsByName("aihao");
        firstChk.onclick=function (){
            if (firstChk.checked){
                for (var i=0;i<aihaos.length;i++){
                    aihaos[i].checked=true;
                }
            }else {
                for (var i=0;i<aihaos.length;i++){
                    aihaos[i].checked=false;
                }
            }
        }
        var all=aihaos.length;
        for (var a=0;a<aihaos.length;a++) {
            aihaos[a].onclick = function () {
                var b = 0;
                for (var i = 0; i < aihaos.length; i++) {
                    if (aihaos[i].checked) {
                        b++;
                    }
                }
                if (b == all) {
                    firstChk.checked = true;
                } else {
                    firstChk.checked = false;
                }
            }
        }
    }
</script>
<input type="checkbox" id="firstChk">全选<br>
<input type="checkbox" name="aihao" value="smoke">抽烟<br>
<input type="checkbox" name="aihao" value="drink">喝酒<br>
<input type="checkbox" name="aihao" value="tt">烫头<br>
</body>
</html>